<?php

namespace brand\components;

use brand\Curd;
use brand\logic\BrandHelper;
use brand\logic\Database;
use brand\tools\Functions;
use think\facade\Db;

class Take extends Component
{

    public $take_options = [];

    public function _init()
    {
        $this->component = 'take';
    }

    public function Form()
    {
        parent::Form();
        $this->form_column->options($this->take_options);

        return $this->form_column;
    }


    /**
     * 表单值字段过滤
     */
    public function checkFormValue()
    {
        if (isset($this->config['form']['props']['limit']) && $this->config['form']['props']['limit'] > 1){
            if ($this->value)  $this->value = explode(',',$this->value);
        }

        $relevancy = $this->config['form']['relevancy'] ?? '';

        $ModelClass = Db::name($relevancy);
        //多选
        if (is_array($this->value)){

            foreach ($this->value as $item) {

                $label = $item;
                if ($ModelClass){
                    $label = Db::name($relevancy)
                        ->where([ ($this->config['form']['props']['selection_value'] ?? 'id') => $item ])
                        ->value( $this->config['form']['props']['selection_label'] ?? 'id' );
                }
                if (!$label) $label = '数据不存在';
                if ($label){
                    $this->take_options[] = ['label'=>$label,'value'=>$item];
                }
            }
        }else{
            //单选
            if ($this->value === 0 ) $this->value = "";
            $label = $this->value;
            if ($ModelClass){
                $label = $ModelClass
                    ->where([ ($this->config['form']['props']['selection_value'] ?? 'id') => $this->value ])
                    ->value( $this->config['form']['props']['selection_label'] ?? 'id' );

            }
            if (!$label) $label = '数据不存在';
            if ($label) {
                $this->take_options = [['label'=>$label,'value'=>$this->value]];
            }

        }
    }

    /**
     * 插入验证
     * @param $key
     * @param $value
     */
    public function checkUpdateData($key, $value)
    {
        if (is_array($value)){
            if ($value){
                $value = implode(',',array_unique($value));
            }else{
                $value = '';
            }
        }



        return $value;
    }

    /**
     * 创建Curd表单
     * @param $field
     * @param $props
     */
    public function DbToCurd($field,$props = [])
    {

        $column = \brand\Brand::Builder()->form_props($props);

        if (!isset($props['limit']) || $props['limit'] == 1){
            $column = $column->search_condition('=');
        }

        $comment = Database::curdComment($field['comment']);


        $labels = [];
        //表单显示字段
        if (isset($comment['options']['table']) && $comment['options']['table']){
            $labels = explode(',',$comment['options']['table']);
        }

        //关联表名称
        if(isset($comment['options']['name'])){
            $relevancy_name = $comment['options']['name'];
        }elseif (Functions::endStr($field['name'],'_ids')){
            $relevancy_name = substr($field['name'],0, -4);
        }elseif (Functions::endStr($field['name'],'_id')){
            $relevancy_name = substr($field['name'],0, -3);
        }else{
            $relevancy_name = $field['name'];
        }




        if ($relevancy_name){
            //关联表的配置
            $relevancy_conf = BrandHelper::getCurdConfigByName($relevancy_name);
            //关联配置存在
            if ($relevancy_conf){

                $pk = isset($relevancy_conf['controller']['pk']) && $relevancy_conf['controller']['pk'] ? $relevancy_conf['controller']['pk'] : 'id';

                $props['unique'] = $props['unique'] ?? true;
                $props['limit'] = $props['limit'] ?? 1;
                $props['url'] = BrandHelper::getUrlPathInfo($relevancy_name.'/index',['selection_key'=>$pk])->build();
                //form表单显示的字段
                $props['selection_label'] = $comment['options']['label'] ?? $pk;
                //form表单索引的字段
                $props['selection_value'] = $pk;

                $column->form_method('take')->form(
                    [
                        'selection_key' => $pk,
                        'relevancy' => $relevancy_name,
                    ]
                )->form_props($props);



                if ($props['limit'] == 1){

                    $column->table([
                        'relevancy' => $relevancy_name,
                        'relevancy_key' => $pk,
                        'relevancy_labels' => $labels
                    ]);

                }
            }
        }

        return $column;
    }


        public function buildConfigColumn($tableConfigValue, $curd_method = 'curd_method')
    {
        $tables = Database::takeTables();

        $options['relevancy'] = \brand\Brand::Builder('关联表','select')->form_options($tables)->build();


        foreach ($tables as $table) {

            //关联字段
            $options['form_'.$table['value'].'_key'] = \brand\Brand::Builder('关联字段','select')
                ->form_options( $table['children'] ?? [] )
                ->form_visible([['prop' => 'relevancy', 'value' => $table['value']]])
                ->build();

            //表单显示字段
            $options['form_'.$table['value'].'_selection_label'] = \brand\Brand::Builder('表单显示字段','select')
                ->form_options( $table['children'] ?? [] )
                ->form_visible([['prop' => 'relevancy', 'value' => $table['value']]])
                ->build();

            //表格显示(可多选)
            $options['table_'.$table['value'].'_labels'] = \brand\Brand::Builder('表格显示(可多选)','select')
                ->form_options( $table['children'] ?? [] )
                ->form_visible([
                    ['prop' => 'relevancy', 'value' => $table['value']],
                    ['prop' => 'relevance_type', 'value' => 0],
                ])
                ->form_props(['multiple'  =>  true])
                ->build();

        }

        $options['relevance_type'] = \brand\Brand::Builder('对应关系','radio')->form_options(BrandHelper::formatOptions(['一对一','一对多']))->build();


        $cloumn = \brand\Brand::Builder('关联配置','arrays')
            ->form_options([$options])
            ->form_props( [
                'append'    =>  $curd_method != 'curd_method'
            ])
            ->form_visible([['prop' => $curd_method, 'value' => 'Take']])
            ->build();




        $relevancy = $tableConfigValue['form']['relevancy'] ?? "";
        $values[] = [
            'relevancy' => $relevancy,
            'relevance_type' => (isset($tableConfigValue['form']['props']['limit']) && $tableConfigValue['form']['props']['limit'] > 1) ? 1 : 0,
            'form_'.$relevancy.'_key' =>   $tableConfigValue['form']['selection_key'] ?? "",
            'form_'.$relevancy.'_selection_label' =>   $tableConfigValue['form']['props']['selection_label'] ?? "",
            'table_'.$relevancy.'_labels' =>   $tableConfigValue['table']['relevancy_labels'] ?? [],
        ];

        return ['column' => $cloumn,'value' => $values];
    }

    public function methodFormConf($form,$table,$params)
    {

        $addon_list = get_addon_list();

        $param = $params['param'][0] ?? [];
        $relevancy = $param['relevancy'] ?? "";
        $relevancy_path = $relevancy;

        foreach ($addon_list as $item) {
            if (!isset($item['table_prefix'])) continue;
            if (strpos($relevancy,$item['table_prefix']) === 0){
                $relevancy_path = "/" . $item['name'] . "/" . ($addon_info['admin'] ?? 'admin') . "/" . str_replace($item['table_prefix'],"",$relevancy);
                break;
            }
        }



        $form['relevancy'] = $relevancy;
        $form['selection_key'] = $param['form_'.$relevancy.'_key'] ?? "";
        $form['props'] = [
            'unique'    =>  true,
            'limit'     =>  $param['relevance_type'] == 0 ? 1 : 999,
            'url'       =>   url($relevancy_path.'/index',['selection_key'=>$form['selection_key']])->build(),
            'selection_label'       =>   $param['form_'.$relevancy.'_selection_label'] ?? "",
            'selection_value'       =>   $form['selection_key'],
        ];
        $table['relevancy'] = $relevancy;
        $table['relevancy_key'] = $form['selection_key'];
        $table['relevancy_labels'] = $param['table_'.$relevancy.'_labels'] ?? [];


        return [$form,$table];
    }

}